<script setup>
import { useUserStore } from '@/store/modules/user'
import { Phone, Lock } from '@element-plus/icons-vue'
import SendMessageBtn from './SendMessageBtn.vue'
import ConfirmForm from './ConfirmForm.vue'
import { PHONE_REGEXP } from '@/utils/regExp'
import { checkPhone } from '@/api/system/app'

// 获取router变量
const vueRouter = useRouter()
// 获取store变量
const userStore = useUserStore()

const formRef = ref()
const step = ref('one')

const formModel = reactive({
  phoneNum: '',
  code: '',
  loginButtonDisabled: false,
  loginButtonLoading: false,
  loginButtonName: '下一步'
})
const formRules = reactive({
  phoneNum: [
    { required: true, message: '请输入手机号！', trigger: 'blur' },
    { pattern: PHONE_REGEXP, trigger: 'blur', message: '请输入正确的手机号码' }
  ],
  code: [{ required: true, message: '请输入短信验证码！', trigger: 'blur' }]
})

const validate = () => {
  formRef.value.validateField(['phoneNum'])
}

const submitForm = () => {
  formModel.loginButtonDisabled = true
  formModel.loginButtonLoading = true
  formRef.value.validate((valid) => {
    if (valid) {
      const param = {
        phoneNum: formModel.phoneNum,
        code: formModel.code
      }
      checkPhone(param)
        .then((res) => {
          step.value = 'two'
        })
        .catch((err) => {
          formModel.loginButtonDisabled = false
          formModel.loginButtonLoading = false
        })
    } else {
      formModel.loginButtonDisabled = false
      formModel.loginButtonLoading = false
    }
  })
}
</script>

<template>
  <el-form v-if="step === 'one'" ref="formRef" :model="formModel" :rules="formRules">
    <el-form-item prop="phoneNum">
      <el-input v-model="formModel.phoneNum" :prefix-icon="Phone" placeholder="请输入手机号" clearable />
    </el-form-item>
    <el-form-item prop="code">
      <div class="flex flex-grow items-center">
        <el-input v-model="formModel.code" type="code" :prefix-icon="Lock" placeholder="请输入短信验证码" clearable />
        <SendMessageBtn operation="FindByPhone" :userName="formModel.phoneNum" @validate="validate" />
      </div>
    </el-form-item>
    <div class="flex justify-center mt-6">
      <el-button
        type="primary"
        @click="submitForm"
        :disabled="formModel.loginButtonDisabled"
        :loading="formModel.loginButtonLoading"
      >
        {{ formModel.loginButtonName }}
      </el-button>
    </div>
  </el-form>
  <ConfirmForm v-else :phoneNum="formModel.phoneNum" />
</template>

<style lang="scss" scoped></style>
